import React from 'react';
import {inject, observer} from 'mobx-react';
import { withRouter, Route } from 'react-router-dom';
import { ListViewPage, ListEditable, Upload, RouteLayout, Form, Browser } from 'weaver-mobile-page';
import { Button, Tools, Icon, Modal, List, Bubble, PullToRefresh, Flex } from 'weaver-mobile';
import { toJS } from 'mobx'
import NoData from '../../../public/NoData';
import MeetingUtil from '../../../util/meetingUtil';
import EditTable from './editTable';
const { FormItem } = List;
const getLabel = Tools.getLabel;
// const List = ListEditable.List
const ButtonGroup = RouteLayout.ButtonGroup;

@inject('viewMeetingStore')
@withRouter
@observer
class TopicView extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            addtopic: true,
            topoicContentHeight: window.innerHeight - 45 - 47,
        };
        this.topicContentHeightRef = React.createRef();
      }
    componentDidMount() {
      const { setState, meetingId ,meetingTopicDefaultValue} = this.props.viewMeetingStore;
      setState({getBaseDetail:false,topic_conditions:[]},this.getDetail);
      //if(meetingTopicDefaultValue == 1) 
      //this.addEditTableNew()
    }

    componentWillReceiveProps (nextProps) {
      const {getBaseDetail,setState} = this.props.viewMeetingStore;
      if(getBaseDetail){
        setState({getBaseDetail:false,topic_conditions:[]},this.getDetail)
      }
    }
    
    shouldComponentUpdate(nextProps) {
      const {setState} = this.props.viewMeetingStore;
      const { location:{ pathname: nP } } = nextProps;
      const { location:{ pathname: p } } = this.props;
      if(nP === '/calendar/detail/topicData/editTopicLayout' && p === '/calendar/detail/topicData') {
        let topic_listRouter = new ListEditable.Store({ route: `${nP}` });
        setState({ topic_list: topic_listRouter });
      } else if(nP === '/calendar/detail/topicData' && p === '/calendar/detail/topicData/editTopicLayout') {
        setState({ topicType: 'view' }, () => {
          this.getDetail();
        });
      }
      return true;
    }

    componentDidUpdate() {
      if(this.topicContentHeightRef && this.topicContentHeightRef.current && this.state.topoicContentHeight !== this.topicContentHeightRef.current.offsetHeight) {
        this.setState({ topoicContentHeight: this.topicContentHeightRef.current.offsetHeight });
      }
    }

    componentWillUnmount() {
      const { setState } = this.props.viewMeetingStore;
      setState({ topicType: 'view' });
    }

    getDetail = ()=>{
      const { getTopic, get_Conditions,get_Data,is_topic,setState, type, meetingId , initTopicList, meetingType, accessoryBaseInfo} = this.props.viewMeetingStore;
      //考虑到刷新的时候
      let typeTemp = type?type:sessionStorage.getItem('type')
      let meetingIdTemp = meetingIdTemp?meetingIdTemp:sessionStorage.getItem('meetingId')
      if(meetingIdTemp === null) {
        meetingIdTemp = ''
      }
      setState({type:typeTemp,meetingId:meetingIdTemp})
      initTopicList();
      get_Data({meetingid: meetingIdTemp}, 'topic');
      get_Conditions({meetingid: meetingIdTemp, secId:accessoryBaseInfo.category}, 'topic');
      setState({is_topic: false});
      
    }

    addEditTable = () => {
        const pathname = this.props.location.pathname;
        const { topic_list } = this.props.viewMeetingStore;
        topic_list.doAdd('',this.onchange);
        this.props.history.push(`${pathname}/editor`);
    }

    addEditTableNew = () => {
      const pathname = this.props.location.pathname;
      const { topic_list } = this.props.viewMeetingStore;
      topic_list.doAdd('',this.onchange);
      //this.props.history.push(`${pathname}/editor`);
  }
 
    onchange = (newData) => {
      let {setState, topic_list, tempUploadStore,topic_initialData} = this.props.viewMeetingStore;
      let obj = {};
      topic_list = toJS(topic_list);
      if (topic_list && topic_list.formList) {
        for(let i in topic_list.formList) {
          obj = {
            ...obj,
            [i]: topic_list.formList[i].uploadFiles
          }
        }
      }
      setState({topic_data: newData, topic_initialData:newData, tempUploadStore: obj });
    }

    itemChange = (content, condition, data, index)=>{
      data = toJS(data);
      let { topic_data, setState, tempUploadStore, topic_list,meetingId, type, arrangeDateLayout, 
        provideInfoLayout, addTopicDoc, videwDatumLayout, getTopicDocList, getTopicDate, 
        topicType,
      } = this.props.viewMeetingStore;
      const {formList} = toJS(topic_list);
      tempUploadStore = toJS(tempUploadStore);
      content = toJS(content);
      condition = toJS(condition);
      let list = formList;
      const _this = this;
      if(type === 'view' && topicType === 'view' && condition.domkey && condition.domkey[0] === "defined_btns") {
        let num = data.doclist ? data.doclist.length : 0;
        if(data.btns !== undefined) {
          return <span className="meeting-topic-item-btns">
            <div className="meeting-topic-datum"
              style={num === 0 ? { visibility: 'hidden' } : {}}
              onClick={() => {
                getTopicDocList({ meetingid: meetingId, topicid: data.id },() => {
                  this.props.history.push(videwDatumLayout.path);
                });
                setState({ topicCurrentId: data.id });
              }}
            >
              <Icon type='note' size='xs'/>
              <label className="meeting-topic-datum-count">{`( ${num} )`}</label>
            </div>
            <div className="meeting-topic-right-btns">
              {data.btns && data.btns.showTimeBtn && <Button inline onClick={()=>{
                const params = {
                  meetingid: meetingId,
                  topicid: data.id
                };
                setState({ topicCurrentId: data.id });
                getTopicDate(params, () => {
                  this.props.history.push(arrangeDateLayout.path);
                });
              }}><Icon type='blog-chidao' size='xs'/>{getLabel('82903','安排时间')}</Button>}
              {data.btns && data.btns.showDocBtn && <Browser
                label="provideInfoLayout"
                store={provideInfoLayout}
                hasAdvanceSerach
                type={37}
                isSingle={true}
                valueArray={[]}
                onChange={(value, valueSpan, valueArray) => {
                  const { topicCurrentId } = _this.props.viewMeetingStore;
                  const params = {
                    meetingid: meetingId,
                    topicid: topicCurrentId,
                    docid: value,
                  };
                  addTopicDoc(params, () => {
                    _this.getDetail()
                  });
                }}
              >
                <Button onClick={() => {
                  setState({ topicCurrentId: data.id });
                }} inline><Icon type='general-purpose-1' size='xs'/>{getLabel('82902','提供资料')}</Button>
              </Browser>}
            </div>
          </span>
        }
      } else if(condition.conditionType == 'CHECKBOX' && topic_data.length > 0){
        if(content == 1){
          return getLabel(163,'是')
        }else{
          return getLabel(161,'否')
        }
      }else{
        return content;
      }
    }

    willCopyData = (allData, copyIds, newData ) => {
      let { topic_data, setState, topicConditionUploadKeys } = this.props.viewMeetingStore;
      let old_datas = toJS(topic_data);
      let temp_topicConditionUploadKeys = toJS(topicConditionUploadKeys);

      copyIds = toJS(copyIds);
      if(temp_topicConditionUploadKeys.length > 0 && Array.isArray(newData)) {
        Array.isArray(temp_topicConditionUploadKeys) && temp_topicConditionUploadKeys.forEach(keys => {
          let tempNewData = [];
          newData.forEach((element, _index) => {
            if(Array.isArray(old_datas)) {
              let copyParentData = old_datas.find(v =>  v.id === copyIds[_index]);
              if(copyParentData) {
                copyParentData = {
                  ...copyParentData,
                  id: element.id,
                  key: element.id,
                  randomFieldId: element.id,
                  topic_data: element.id,
                };
                element = {
                  ...element,
                  ...copyParentData
                };
              }
            }
            tempNewData.push(element);
          });
          old_datas = old_datas.concat(tempNewData);
        }) 
      }
      setState({ topic_data: old_datas });
    }

    createTopic = () => {
        const { topicList, topic_list, topic_data, topic_initialData, topic_conditions, setState } = this.props.viewMeetingStore;
        let field = [];
        let addVisible = topic_data&&topic_data.length === 0 ? 'none' : 'block';
        field.push(
          <div className='topic-list' key='topic-list' 
                    style={{display: addVisible,}}>
             {topic_list&&topic_conditions&&<ListEditable
                title={getLabel(501093,"编辑议程")}
                rowKey="id"
                store={topic_list}
                data={topic_data}
                initData={topic_data}
                conditions={toJS(topic_conditions)}
                onChange={this.onchange}
                willCopy={this.willCopyData}
                getItemContent={(content, condition, data, index)=>{return this.itemChange(content, condition, data, index)}}
                willDelete={newData => new Promise((resolve) => {
                    Modal.alert(getLabel(15097,'确定要删除吗？'), '', [
                    { text: getLabel(31129,'取消'), onPress: () => resolve(false) },
                    {
                        text: getLabel(826,'确定'),
                        onPress: () => {
                        resolve(newData);
                        },
                    },
                    ]);
                })}
                />
              }
          </div>
        )

        topic_data&&topic_data.length === 0 && field.push(
            <div className='topic-nodata' key='topic-nodata'>
                <div className='icon'>
                    <Icon type='meeting-add-meeting' size='lg'/>
                </div>
                <label>{getLabel(501094,'在这里，你可以添加会议议程')}</label>
                <div className='btn-tianjia'>
                    <Button type='primary' onClick={() => {this.addEditTable()}}>{getLabel(384113,'添加')}</Button>
                </div>
            </div>
        )

        return field;
    }

    getLoading = () => {
      return (
        <div className='loaidng-icon' key='loading' style={{position: 'fixed', left: '50%', top: '50%'}}>
          <Icon type='loading' size='lg'/>
        </div>
      );
    }

    getFields = () => {
      const { arrangeDateForm } = this.props.viewMeetingStore;
      const { conditioninfo, isInit } = arrangeDateForm;
      const fields = [];
      if (isInit) {
        conditioninfo.forEach((group) => {
          group.items.forEach((field) => {
            fields.push(<Form.Item
              key={field.domkey.join('__')}
              form={arrangeDateForm}
              fieldConfig={field}
              onChange={arrangeDateForm.onChange}
            />);
          });
        });
      }
      return fields;
    }

    getDatepicker = () => {
      let { topicArrangeDates, setState } = this.props.viewMeetingStore;
      topicArrangeDates = toJS(topicArrangeDates);
      return (
        <EditTable
          showAdd={true}
          showCopy={true}
          showDelete={true}
          data={topicArrangeDates}
          onChange={(data) => { setState({ topicArrangeDates: data }); }}
        />
      );
    }

    deleteDatum = (item) => {
      let id = item[0] ? item[0].docId : '';
      const { delTopicDoc, getTopicDocList, meetingId, topicCurrentId } = this.props.viewMeetingStore;
      Modal.alert(getLabel(15097,'确定要删除吗？'), '', [
        { text: getLabel(31129,'取消'), onPress: () => {}
        },
        {
          text: getLabel(826,'确定'),
          onPress: () => {
            delTopicDoc({id: id}, () => {
              getTopicDocList({ meetingid: meetingId, topicid: topicCurrentId });
              this.getDetail();
            });
          },
        },
      ]);
    }

    getDatumLists = () => {
      let { topicDocList, datumForm } = this.props.viewMeetingStore;
      topicDocList = toJS(topicDocList);
      let fields = [];
      let listItems = [];
      Array.isArray(topicDocList) && topicDocList.forEach(element => {
        if(element.items && (element.items[0] === undefined || element.items[1] === undefined)) return;
        listItems.push(
          <List.Item 
            multipleLine 
            className={'meeting-datum-item'}
            key={element.items[0].domkey[0]}
            extra={<Icon type='delete' onClick={() => this.deleteDatum(element.items)}/>} 
          >
            <Form.Item
              
              key={element.items[0].domkey.join('__')}
              form={datumForm}
              fieldConfig={element.items[0]}
            />
            <List.Item.Brief>
              <Form.Item
                key={element.items[1].domkey.join('__')}
                form={datumForm}
                fieldConfig={element.items[1]}
              />
            </List.Item.Brief>
          </List.Item>
        );
      });
      fields.push(
        <List className="meeting-datum-lists">
          { listItems }
        </List>
      );
      return fields;
    }

    saveTopicDate = (callback) => {
      let { saveTopicDate, topicArrangeDates, topicCurrentId, meetingId } = this.props.viewMeetingStore;
      topicArrangeDates = toJS(topicArrangeDates);
      let dateItems = {};
      if(Array.isArray(topicArrangeDates)) {
        let rowPositon = 0;
        let isRequired = false;
        let beginThanEnd = false;
        for(let v in topicArrangeDates) {
          rowPositon ++;
          if(topicArrangeDates[v] && topicArrangeDates[v].date) {
            if(topicArrangeDates[v].date.length === 0 || topicArrangeDates[v].date[0] === undefined || topicArrangeDates[v].date[1] === undefined
              || topicArrangeDates[v].date[0] === '' || topicArrangeDates[v].date[1] === ''
              ) {
              isRequired = true;
              break;
            }
            if(!(topicArrangeDates[v].date[0] < topicArrangeDates[v].date[1])) {
              beginThanEnd = true;
              break;
            }
          }
        }
        if(isRequired || beginThanEnd) {
          if(isRequired) {
            Bubble.error(getLabel('521799','第${num}行必填项未填写！').replace('${num}', rowPositon), 2);
          }else if(beginThanEnd) {
            Bubble.error(getLabel('521800','第${num}开始时间应该小于结束时间！').replace('${num}', rowPositon), 2);
          }
        } else {
          topicArrangeDates.forEach((res, index) => {
            if(res.date === undefined) return;
            const getDateTime = (date) => {
              let dateTime = ['', ''];
              if(typeof date === 'string') {
                dateTime = date.split(' ');
              }
              return dateTime;
            }
            dateItems = {
              ...dateItems,
              [`begindate_${index}`]: getDateTime(res.date[0])[0],
              [`begintime_${index}`]: getDateTime(res.date[0])[1],
              [`enddate_${index}`]: getDateTime(res.date[1])[0],
              [`endtime_${index}`]: getDateTime(res.date[1])[1],
            };
          });
          const params = {
            meetingid: meetingId,
            topicid: topicCurrentId,
            rows: topicArrangeDates.length,
            ...dateItems
          };
          saveTopicDate(params, () => {
            typeof callback === 'function' && callback();
            // this.props.history.go(-1);
          });
        }
      }
    }

    getRouterLayout = () => {
      let { arrangeDateLayout, videwDatumLayout, topicArrangeDates, editTopicLayout, topic_data, saveTopicTidy,
        topicCurrentId, meetingId, topic_list
      } = this.props.viewMeetingStore;
      let routerLayout = [];
      let arrangeBtns = [
        {
          key: 'cancel',
          text: getLabel(31129,'取消'),
          // disabled:onLoading,
          onClick: () => { this.props.history.go(-1); },
        },
        {
          key: 'submit',
          text: getLabel(725, '提交'),
          type: 'primary',
          // disabled:onLoading,
          onClick: () => {
            this.saveTopicDate(()=>{
              this.getDetail();
              this.props.history.go(-1);
            });
          },
        },
      ];
      let editTopicBtns = [
        {
          key: 'cancel',
          text: getLabel(31129,'取消'),
          onClick: () => { this.props.history.go(-1); },
        },
        {
          key: 'submit',
          text: getLabel(725, '提交'),
          type: 'primary',
          onClick: () => {
            topic_data = toJS(topic_data);
            let params = {
              meetingid: meetingId,
              topicrows: topic_data.length,
            };
            Array.isArray(topic_data) && topic_data.forEach((v, index) => {
              delete v.btns;
              delete v.doclist;
              for(let t in v) {
                let i = `${t}_${index+1}`;
                if(Array.isArray(v[t])) {
                  let objIds = [];
                  v[t].forEach(res => {
                    objIds.push(res.fileid);
                  });
                  v[t] =  objIds.join(',');
                }
                params = {
                  ...params,
                  [i]: v[t]
                }
              }
            });
            let canSave = true;
            topic_list.doValidate( (pass, id, result) => {
              if(!pass) {
                canSave = false;
                const form = topic_list.formList[id]; // 获取报错的form
                const { message, domkey } = result;
                topic_list.setState({ editingKey: id });
                this.props.history.push(topic_list.pathToEditor); // 跳转到编辑页面
                setTimeout(() => { // 等待页面渲染
                  Bubble.error(message, 1, { top: '50%' }); // 错误提示
                  form.focusField(domkey); // 定位到错误项
                }, 200);
                return;
              }
            });
            canSave && saveTopicTidy(params, () => {
              this.props.history.go(-1);
              this.getDetail();
            });
          },
        },
      ];
      routerLayout.push( // 安排时间
        <Route
          key={arrangeDateLayout.id}
          path={arrangeDateLayout.path}
          render={() => (
            <RouteLayout>
              <div
                key="wmPoutePage-arrangeDate"
                className="wm-route-layout wm-demo-route-layout-page meeting-topic-arrangeDate"
              >
                <div style={{
                  height: 'calc(100% - 48px)'
                }}>
                  { this.getDatepicker() }
                </div>
                <ButtonGroup data={arrangeBtns}/>
              </div>
            </RouteLayout>
          )}
        />
      );

      routerLayout.push( // 查看资料
        <Route
          key={videwDatumLayout.id}
          path={videwDatumLayout.path}
          render={() => (
            <RouteLayout>
              <div
                key="wmPoutePage-videwDatumLayout"
                className="wm-route-layout wm-demo-route-layout-page meeting-topic-videwDatumLayout"
              >
                { this.getDatumLists() }
              </div>
            </RouteLayout>
          )}
        />
      );

      routerLayout.push( // 整理议程
        <Route
          key={editTopicLayout.id}
          path={editTopicLayout.path}
          render={() => (
            <RouteLayout>
              <div
                key="wmPoutePage-videwDatumLayout"
                className="wm-route-layout wm-demo-route-layout-page meeting-topic-editor topic-service-content"
              >
                <div style={{
                  height: 'calc(100% - 48px)',
                  overflow: 'auto'
                }}>
                  { this.createTopic() }
                </div>
                <ButtonGroup data={editTopicBtns}/>
              </div>
            </RouteLayout>
          )}
        />
      );

      return(routerLayout);
    }

    render() {
        let { topicList,topic_list, type , topic_conditions, topicViewTopicConditions, topic_data, loadding, topicDocList, topicType } = this.props.viewMeetingStore;
        const { addtopic, topoicContentHeight } = this.state;
        const topicHeight = this.getHeight();
        topic_data = toJS(topic_data);
        topic_conditions = topicViewTopicConditions; // 查看时
        topic_conditions = toJS(topic_conditions);
        topicDocList = toJS(topicDocList);
        return (
        <Flex className="meeting-topic-container" style={{ height: '100%' }} defaultprops={this}>
          <div className={'topic-service-content tabContentHeight'}>
            <div className={topicList.data.length===0 ? 'topicFormDiv meeting-topic-hascontent': 'topicFormDiv'} topic_data={topic_data} topic_conditions={topic_conditions}  ref={this.topicContentHeightRef}>
              {loadding && this.getLoading()}
              {
                type === 'view' ?
                <PullToRefresh
                  className={topicList.data.length===0 ? 'meeting-topic-pull-to-refresh meeting-no-data' : 'meeting-topic-pull-to-refresh'}
                  direction={'down'}
                  damping={60}
                  style={{
                    height: topoicContentHeight,
                    overflow: 'auto',
                  }}
                  refreshing={loadding}
                  onRefresh={() => {
                    this.getDetail();
                  }}
                >
                  {topicList.data.length===0?<NoData/>:
                    <div
                      // style={{
                      //   height: topoicContentHeight,
                      //   overflow: 'auto',
                      // }}
                    >
                      {
                        (topic_conditions&&<ListEditable.List
                          mainStore={topic_list}
                          tableStore={topic_list}
                          store={topicList}
                          onRowSelect = {()=>{return;}}
                          onRowClick = {()=>{return;}}
                          conditions = {topic_conditions}
                          getItemContent={(content, condition, data, index)=>{return this.itemChange(content, condition, data, index)}}
                        />)
                      }
                    </div>
                  }
                </PullToRefresh>
                :
                this.createTopic() 
              }
            </div>
            <div topicDocList={topicDocList}>
              { this.getRouterLayout() }
            </div>
          </div>
        </Flex>
        )
    }

    getHeight = () => {
      return document.body.clientHeight - MeetingUtil.getTabHeight();
    }
}

export default TopicView;